package com.pinyoumei.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.pinyoumei.base.ResponseResult;
import com.pinyoumei.component.JedisSingleClient;
import com.pinyoumei.constans.Constants;
import com.pinyoumei.mapper.TbUserMapper;
import com.pinyoumei.mq.RegisterMailboxProducer;
import com.pinyoumei.pojo.TbUser;
import com.pinyoumei.pojo.TbUserExample;
import com.pinyoumei.pojo.TbUserExample.Criteria;
import com.pinyoumei.service.MemberService;
import com.pinyoumei.utils.IDUtils;
import com.pinyoumei.utils.JsonUtils;
import com.pinyoumei.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;


@Slf4j
@RestController
public class MemberServiceImpl implements MemberService {
	
	@Autowired
	private TbUserMapper userMapper;
	
	@Autowired
	private RegisterMailboxProducer registerMailboxProducer;
	
	@Autowired
	private JedisSingleClient jedisSingleClient;
	
	
	/**
	 * localhost:8888/member/testRest
	 */
	@Override
	public Map<String, Object> testRest() {
		Map<String, Object> result = new HashMap<>();
		result.put("errorCode", "200");
		result.put("errorMsg", "success");
		return result;
	}

	/**
	 * localhost:8888/member/testJsonString
	 */
	@Override
	public String testJsonString() {
		ResponseResult result=new ResponseResult(200,"success","Welcome");
		return JsonUtils.objectToJson(result);
	}

	/**
	 * localhost:8888/member/findUserById?userId=1
	 */
	@Override
	public String findUserById(Long userId) {
		TbUser user=userMapper.selectByPrimaryKey(userId);
		ResponseResult result=new ResponseResult(200,"查询成功","");
		if(null!=user){
			result.setData(user);
			return JsonUtils.objectToJson(result);
		}
		result.setCode(400);
		result.setMsg("查询的用户不存在");
		return JsonUtils.objectToJson(result);
	}

	/**
	 * 注册用户,RabbitMQ异步发邮件
	 */
	@Override
	public String registerUser(@RequestBody TbUser user) {
		user.setCreated(new Date());
		user.setUpdated(new Date());
		String password=user.getPassword();
		user.setPassword(MD5Util.MD5(password));
		user.setAccountBalance(0L);
		user.setExperienceValue(0);
		user.setIsEmailCheck("0");
		user.setIsMobileCheck("0");
		user.setUserLevel(0);
		int result=userMapper.insertSelective(user);
		if(result==1){
			ResponseResult response=new ResponseResult(200,"success","用户注册成功");
			// 采用异步方式发送消息
			String email = user.getEmail();
			String json = getEmailJson(email);
			log.info("####推送消息到消息服务平台####json:{}", json);
			sendMsg(json);
			return JsonUtils.objectToJson(response);
		}
		ResponseResult response=new ResponseResult(500,"fail","用户注册失败");
		return JsonUtils.objectToJson(response);
	}

	private String getEmailJson(String email) {
		JSONObject rootJson = new JSONObject();
		JSONObject header = new JSONObject();
		header.put("interfaceType", Constants.MSG_EMAIL);
		JSONObject content = new JSONObject();
		content.put("email", email);
		rootJson.put("header", header);
		rootJson.put("content", content);
		return rootJson.toJSONString();
	}
	
	private void sendMsg(String json) {
		registerMailboxProducer.sendMsg(json);
	}


	@Override
	public String login(@RequestParam("userName")String userName,@RequestParam("password")String password) {
		// 1.验证参数
		if(StringUtils.isEmpty(userName)){
			ResponseResult result=new ResponseResult(201,"用戶名称不能为空!","用户登录失败");
			return JsonUtils.objectToJson(result);
		}
		if(StringUtils.isEmpty(password)){
			ResponseResult result=new ResponseResult(201,"密码不能为空!","用户登录失败");
			return JsonUtils.objectToJson(result);
		}
		//2.数据库查找用户
		String newpassword=MD5Util.MD5(password);
		TbUserExample example=new TbUserExample();
		Criteria criteria=example.createCriteria();
		criteria.andUsernameEqualTo(userName);
		criteria.andPasswordEqualTo(newpassword);
		List<TbUser> list=userMapper.selectByExample(example);
		if(list==null||list.size()==0){
			ResponseResult result=new ResponseResult(201,"用户不存在!","");
			return JsonUtils.objectToJson(result);
		}
		// 3.如果账号密码正确，对应生成token
		String memberToken=IDUtils.generateMemberToken();
		TbUser tbuser=list.get(0);
		tbuser.setPassword("");
		jedisSingleClient.set(memberToken, JsonUtils.objectToJson(tbuser));
		jedisSingleClient.expire(memberToken,60*60*24*14);
		//4. token写会客户端,浏览器采用cookie,app用文件方式保存
		ResponseResult result=new ResponseResult(200,"用户登录成功!",memberToken);
		return JsonUtils.objectToJson(result);
	}

	@Override
	public String getUserByTokenFromRedis(@RequestParam("token")String token) {
		return jedisSingleClient.get(token);
	}

	/**
	 * localhost:8888/member/login
	 * 用户登录
	 */
	/**
	@Override
	public String login(HttpServletRequest request, HttpServletResponse response) {
		
		// 1.验证参数
		String userName=request.getParameter("userName");
		if(StringUtils.isEmpty(userName)){
			ResponseResult result=new ResponseResult(201,"用戶名称不能为空!","");
			return JsonUtils.objectToJson(result);
		}
		String password=request.getParameter("password");
		if(StringUtils.isEmpty(password)){
			ResponseResult result=new ResponseResult(201,"密码不能为空!","");
			return JsonUtils.objectToJson(result);
		}
		//2.数据库查找用户
		String newpassword=MD5Util.MD5(password);
		TbUserExample example=new TbUserExample();
		Criteria criteria=example.createCriteria();
		criteria.andUsernameEqualTo(userName);
		criteria.andPasswordEqualTo(newpassword);
		List<TbUser> list=userMapper.selectByExample(example);
		if(list==null||list.size()==0){
			ResponseResult result=new ResponseResult(201,"用户名密码错误!","");
			return JsonUtils.objectToJson(result);
		}
		// 3.如果账号密码正确，对应生成token
		String memberToken=IDUtils.generateMemberToken();
		// 4.存放redis，key为token value 为 user信息
		log.info("####生成用户token:"+memberToken);
		TbUser user=list.get(0);
		user.setPassword("");
		jedisSingleClient.set(memberToken, JsonUtils.objectToJson(user));
		jedisSingleClient.expire(memberToken,60*60*24*14);
		//5. token写会客户端保存,浏览器采用cookie,app用文件方式保存
		CookieUtils.setCookie(request, response, "TT_TOKEN", memberToken, 60*60*24*14);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("memberToken", memberToken);
		map.put("member", JsonUtils.objectToJson(list.get(0)));
		ResponseResult result=new ResponseResult(200,"用户登录成功!",map);
		return JsonUtils.objectToJson(result);
	}
	*/
}
